package com.motorola.dp.jenkinsmonitor.service.util.dom;

import javax.annotation.PostConstruct;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

@Service("domUtilityService")
public class DefaultDomUtilityService implements DomUtilityService {

    @Value("#{T(javax.xml.parsers.DocumentBuilderFactory).newInstance()}")
    private DocumentBuilderFactory docBuilderFactory;

    private DocumentBuilder docBuilder;

    @PostConstruct
    public void afterPropertiesSet() throws ParserConfigurationException {
        docBuilderFactory.setNamespaceAware(false);
        docBuilderFactory.setValidating(false);
        docBuilderFactory.setFeature("http://xml.org/sax/features/namespaces", false);
        docBuilderFactory.setFeature("http://xml.org/sax/features/validation", false);
        docBuilderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
        docBuilderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        docBuilder = docBuilderFactory.newDocumentBuilder();
    }

    public void attachToSeparateDocument(Element domNode) {
        Document newDocument = docBuilder.newDocument();
        newDocument.adoptNode(domNode);
        newDocument.appendChild(domNode);
    }

    public void setDocBuilderFactory(DocumentBuilderFactory docBuilderFactory) {
        this.docBuilderFactory = docBuilderFactory;
    }

    public void setDocBuilder(DocumentBuilder docBuilder) {
        this.docBuilder = docBuilder;
    }
}
